const app = getApp();

Page({
  data: {
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth(), 
    calendarDays: [],
    todos: [],
    monthPlans: [],
    completedCount: 0,
    selectedDate: null,
    dailyTodos: [],
    monthlyPlansByMonth: [],
    theme: {}
  },

  getMonthPlans: function(monthIndex) {
    return this.data.monthPlans.filter(plan => plan.month === monthIndex);
  },
  // 获取当天日期字符串
  getTodayDateString: function() {
    const today = new Date();
    return this.formatDate(today);
  },

  // 获取n天后的日期字符串
  getDateStringAfterDays: function(days) {
    const date = new Date();
    date.setDate(date.getDate() + days);
    return this.formatDate(date);
  },

  // 格式化日期
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  onLoad: function() {
    const today = this.getTodayDateString();
    const tomorrow = this.getDateStringAfterDays(1);
    
    this.setData({
      todos: [
        { id: 1, content: "完成高数习题9", completed: true, date: today },
        { id: 2, content: "完成人机交互实验", completed: false, date: today },
        { id: 3, content: "长难句分析2", completed: false, date: today },
        { id: 4, content: "背诵单词100个", completed: true, date: tomorrow }
      ],
      monthPlans:[
          { id: 1, month: 0, content: "完成高数上", completed: true },
          { id: 2, month: 0, content: "背单词200个", completed: false },
          { id: 3, month: 1, content: "准备英语四级", completed: false }
      ]
    }, () => {
      const dailyTodos = this.data.todos.filter(todo => todo.date === today);
      const completedCount = dailyTodos.filter(todo => todo.completed).length;
      
      this.setData({
        selectedDate: today,
        dailyTodos: dailyTodos,
        completedCount: completedCount
      });
      // 计算每个月的计划
      const monthlyPlansByMonth = [];
      for (let i = 0; i < 12; i++) {
        monthlyPlansByMonth[i] = this.data.monthPlans.filter(plan => plan.month === i);
      }
      this.setData({ monthlyPlansByMonth });
      this.generateCalendar();
    });
    // 获取全局主题
    this.setData({
      theme: app.globalData.theme
    });
  },

  // 生成日历数据
  generateCalendar: function() {
    const year = this.data.currentYear;
    const month = this.data.currentMonth;
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const firstDay = new Date(year, month, 1).getDay();
    const prevMonthDays = new Date(year, month, 0).getDate();
    const days = [];
    
    // 上个月的最后几天
    const prevMonthDaysToShow = firstDay === 0 ? 6 : firstDay;
    for (let i = prevMonthDaysToShow; i > 0; i--) {
      days.push({
        day: prevMonthDays - i + 1,
        isCurrentMonth: false,
        isPadding: true
      });
    }
    
    // 当前月的天数
  for (let i = 1; i <= daysInMonth; i++) {
    const today = new Date();
    const isToday = year === today.getFullYear() && 
                   month === today.getMonth() && 
                   i === today.getDate();
    
    const dateStr = this.formatDate(new Date(year, month, i));
    // 检查该日期是否有任务
    const hasTodos = this.data.todos.some(todo => todo.date === dateStr);
      
      days.push({
        day: i,
        date: dateStr,
        isCurrentMonth: true,
        isToday: isToday,
        hasTodos: hasTodos,
        isPadding: false
      });
    }
    
    // 下个月的前几天
    const totalCells = Math.ceil(days.length / 7) * 7;
    const nextMonthDays = totalCells - days.length;
    for (let i = 1; i <= nextMonthDays; i++) {
      days.push({
        day: i,
        isCurrentMonth: false,
        isPadding: true
      });
    }
    
    this.setData({ calendarDays: days });
  },

  // 点击日期
  selectDate: function(e) {
    const selectedDate = e.currentTarget.dataset.date;
    if (!selectedDate || !e.currentTarget.dataset.isCurrentMonth) return;
    
    const dailyTodos = this.data.todos.filter(todo => todo.date === selectedDate);
    const completedCount = dailyTodos.filter(todo => todo.completed).length;  // 只计算选中日期的完成数
    this.setData({
      selectedDate: selectedDate,
      dailyTodos: dailyTodos
    });
  },

  // 切换TODO状态
  toggleTodo: function(e) {
    const id = e.currentTarget.dataset.id;
    const todos = this.data.todos.map(todo => {
      if (todo.id === id) {
        return { ...todo, completed: !todo.completed };
      }
      return todo;
    });
    
    // 更新当天完成的任务数
    const selectedDate = this.data.selectedDate;
    const dailyTodos = todos.filter(todo => todo.date === selectedDate);
    const completedCount = dailyTodos.filter(todo => todo.completed).length;
    
    this.setData({
      todos: todos,
      completedCount: completedCount,
      dailyTodos: dailyTodos
    });
  },

  // 切换月计划状态
  toggleMonthPlan: function(e) {
    const id = e.currentTarget.dataset.id;
    const monthPlans = this.data.monthPlans.map(plan => {
      if (plan.id === id) {
        return { ...plan, completed: !plan.completed };
      }
      return plan;
    });

    // 更新每个月的计划
    const monthlyPlansByMonth = [];
    for (let i = 0; i < 12; i++) {
      monthlyPlansByMonth[i] = monthPlans.filter(plan => plan.month === i);
    }

    this.setData({ monthPlans, monthlyPlansByMonth });
  },

  // 切换月份
  changeMonth: function(e) {
    const direction = e.currentTarget.dataset.direction;
    let newMonth = this.data.currentMonth;
    let newYear = this.data.currentYear;
    
    if (direction === 'prev') {
      newMonth--;
      if (newMonth < 0) {
        newMonth = 11;
        newYear--;
      }
    } else {
      newMonth++;
      if (newMonth > 11) {
        newMonth = 0;
        newYear++;
      }
    }
    
    this.setData({
      currentYear: newYear,
      currentMonth: newMonth
    }, () => {
      this.generateCalendar();
    });
  }
});